package com.zjmzxfzhl.modules.app.controller;

import java.util.*;

import javax.validation.Valid;

import com.zjmzxfzhl.common.log.annotation.Log;
import com.zjmzxfzhl.modules.app.entity.AppDir;
import com.zjmzxfzhl.modules.app.entity.AppStock;
import com.zjmzxfzhl.modules.app.form.AppDocVo;
import com.zjmzxfzhl.modules.app.form.AppProdVerVo;
import com.zjmzxfzhl.modules.app.form.AppProdVo;
import com.zjmzxfzhl.modules.app.form.DirCrumbVo;
import com.zjmzxfzhl.modules.app.service.AppDirService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zjmzxfzhl.common.core.Result;
import com.zjmzxfzhl.common.core.base.BaseController;
import com.zjmzxfzhl.modules.app.entity.AppProdVer;
import com.zjmzxfzhl.modules.app.service.AppProdVerService;

/**
 * Controller
 * 
 * @author 张森荣
 */
@RestController
@RequestMapping("/app/prodVer")
public class AppProdVerController extends BaseController {
    @Autowired
    private AppProdVerService appProdVerService;
    @Autowired
    private AppDirService appDirService;

    /**
     * 自定义查询列表
     * 
     * @param appProdVerVo
     * @param current
     * @param size
     * @return
     */
//    @PreAuthorize("@elp.single('app:prodVer:list')")
    @GetMapping(value = "/list")
    public Result list(AppProdVerVo appProdVerVo, @RequestParam Integer current, @RequestParam Integer size) {
        Map<String,Object> resultMap=new HashMap();
        //查询文档条件
        boolean bool=true;//是否查询目录
        //查询目录条件
        List<AppDir> appDirList=new ArrayList<>();
        int dirTotal=0;
        if (bool) {
            AppDir appDir=new AppDir();
            appDir.setDirType("09");
            appDir.setDirTypeId(appProdVerVo.getProdId());
            if(appProdVerVo.getDirId()==null||"".equals(appProdVerVo.getDirId())){
                appDir.setDirLevel("1");
            }else {
                appDir.setParentDirId(appProdVerVo.getDirId());
            }
            //查出目录
            appDirList = appDirService.getList(new Page<AppDir>(current, size), appDir);
            dirTotal=appDirService.selectRowCount(appDir);
        }
        resultMap.put("dirData",appDirList);
        //查出文档补全
        int verTotal=appProdVerService.selectRowCount(appProdVerVo);
        int total=dirTotal+verTotal;
        resultMap.put("total",total);
        List<AppProdVerVo> appVerVoList =new ArrayList<>();
        int verCurrent=0;//文档页数
        int verSize=0;//文档页数大小
        if((dirTotal/size)<current){//当前页目录数量不够
            int lack = current * size - dirTotal;
            if (appDirList.size()>0) {//当前页存在目录
                verCurrent = 1;
                verSize = lack % size;
                appVerVoList = appProdVerService.getList(new Page<AppProdVerVo>(verCurrent, verSize), appProdVerVo);
            }else {//当前页不存在目录
                verCurrent = current-(dirTotal/size+1);
                verSize = size;
                List<AppProdVerVo> appVerVos= appProdVerService.getList(new Page<AppProdVerVo>(verCurrent, verSize), appProdVerVo);
                for(int i=0;i<size-lack % size && appVerVos.size() > i;i++){
                    appVerVoList.add(appVerVos.get(appVerVos.size()-i-1));
                }
                int newNum=appVerVoList.size();
                if(verCurrent==0){//0页与1页相同避免重复查询
                    verCurrent = verCurrent+1;
                }
                verCurrent = verCurrent+1;
                appVerVos= appProdVerService.getList(new Page<AppProdVerVo>(verCurrent, verSize), appProdVerVo);
                for (int i = 0; i < size-newNum && appVerVos.size() > i; i++) {
                    appVerVoList.add(appVerVos.get(i));
                }
            }
        }
        resultMap.put("verData", appVerVoList);
        if (appProdVerVo.getDirId() != null && !"".equals(appProdVerVo.getDirId())) {
            List<DirCrumbVo> dirCrumbVos = appDirService.dirCrumb(appProdVerVo.getDirId());
            resultMap.put("dirCrumb", dirCrumbVos);
        }else
        {
            resultMap.put("dirCrumb", new ArrayList<>());
        }

        return Result.ok(resultMap);
    }

//    @PreAuthorize("@elp.single('app:prodVer:list')")
    @GetMapping(value = "/queryById")
    public Result queryById(@RequestParam String id) {
        AppProdVerVo appProdVerVo = appProdVerService.queryById(id);
        if(appProdVerVo==null){
            return Result.ok();
        }
        return Result.ok(appProdVerVo);
    }

    /**
     * @功能：新增
     * @param appProdVer
     * @return
     */
//    @PreAuthorize("@elp.single('app:prodVer:save')")
    @PostMapping(value = "/save")
    public Result save(@Valid @RequestBody AppProdVer appProdVer) {
        Boolean bool =  appProdVerService.saveAppProdVer(appProdVer);
        if (bool == false) {
            return Result.error("添加失败");
        }
        AppProdVer result = appProdVerService.queryById(appProdVer.getVerId());
        return Result.ok(result);
    }

    /**
     * @功能：修改
     * @param appProdVer
     * @return
     */
//    @PreAuthorize("@elp.single('app:prodVer:update')")
    @PutMapping(value = "/update")
    public Result update(@Valid @RequestBody AppProdVer appProdVer) {
        appProdVerService.updateById(appProdVer);
        return Result.ok();
    }

    /**
     * @功能：批量删除
     * @param ids
     * @return
     */
//    @PreAuthorize("@elp.single('app:prodVer:delete')")
    @DeleteMapping(value = "/delete")
    public Result delete(@RequestParam String ids) {
        if (ids == null || ids.trim().length() == 0) {
            return Result.error("ids can't be empty");
        }
        String[] idsArr = ids.split(",");
        if (idsArr.length > 1) {
            appProdVerService.removeByIds(Arrays.asList(idsArr));
        } else {
            appProdVerService.removeById(idsArr[0]);
        }
        return Result.ok();
    }

    /**
     * @功能： 发布变更{00.待审批,01.审批中,02.审批过,03.已驳回,04.已关闭}
     * @param verId
     * @param status
     * @return
     */
//    @PreAuthorize("@elp.single('app:Doc:update')")
    @PutMapping(value = "/verChange")
    public Result verChange(@RequestParam String verId,@RequestParam String status) {
        Boolean result =true;
        switch (status) {
            case "00": //待审批
                result =appProdVerService.pendingTrial(verId);
                break;
            case "01": //审批中
                result =appProdVerService.inReview(verId);
                break;
            case "02": //审批过
                result =appProdVerService.reviewed(verId);
                break;
            case "03": //已驳回
                result =appProdVerService.reject(verId);
                break;
            case "04": //已关闭
                result =appProdVerService.close(verId);
                break;
            default: return Result.error("查找文档状态失败！");
        }
        if(result==false){
            return Result.error("文档状态更改失败！");
        }
        return Result.ok();
    }

    @Log(value = "启动文档审批流程实例")
    @PostMapping(value = "/processStart")
    @Transactional(rollbackFor = Exception.class)
    public Result processStart(@RequestParam String verId) {
        Boolean result =appProdVerService.processStart(verId);
        return Result.ok();
    }

    @GetMapping(value = "/procProdVer")
    public Result procProdVer(@RequestParam String processInstanceId) {
        List<AppProdVerVo> appProdVerVoList =appProdVerService.procProdVer(processInstanceId);
        AppProdVerVo result=null;
        if(appProdVerVoList.size()>0){
            result=appProdVerVoList.get(0);
        }
        return Result.ok(result);
    }
}
